# encoding=utf-8
import os
import logging
import random
import threading
import requests
from scrapy.utils.project import get_project_settings

from zc_core.middlewares.proxies.proxy_facade import ProxyFacade
from zc_core.plugins.verify_code import VerifyCode
from zc_core.util.encrypt_util import short_uuid

logger = logging.getLogger('session')


class SessionHelper(object):
    _instance_lock = threading.Lock()
    _biz_inited = False

    session_pool = list()
    min_pool_size = 2
    session_pool.append('83ca0219-78c8-40d3-bdf5-d97ab7c1d32f')
    session_pool.append('83ca0219-78c8-40d3-bdf5-d97ab7c1d31f')
    def __init__(self):
        if not self._biz_inited:
            self._biz_inited = True
            self.proxy_facade = ProxyFacade()
        self.reload(self.min_pool_size)

    def __new__(cls, *args, **kwargs):
        if not hasattr(SessionHelper, '_instance'):
            with SessionHelper._instance_lock:
                if not hasattr(SessionHelper, '_instance'):
                    SessionHelper._instance = object.__new__(cls)
        return SessionHelper._instance

    def get_session(self):
        if not self.session_pool or len(self.session_pool) < self.min_pool_size:
            # 初始化/补充
            self.reload(self.min_pool_size)
        return random.choice(self.session_pool)

    def remove(self, session_id):
        try:
            self._instance_lock.acquire()
            logger.info('移除SESSION: session=%s' % session_id)
            if self.session_pool and session_id in self.session_pool:
                self.session_pool.remove(session_id)
        except Exception as e:
            logging.error(e)
        finally:
            self._instance_lock.release()

    def reload(self, max):
        try:
            self._instance_lock.acquire()
            for idx in range(1, max):
                self._reload_session()
        except Exception as e:
            logging.error(e)
        finally:
            self._instance_lock.release()

    def _reload_session(self):
        # proxy = self.proxy_facade.get_proxy()
        # proxies = dict()
        # if proxy and 'NO_PROXY' not in proxy:
        #     proxies['http'] = proxy
        r = requests.get(
            url='http://222.143.21.205:8081/',
            # proxies=proxies,
            headers={
                'Host': '222.143.21.205:8081',
                'Connection': 'keep-alive',
                'Upgrade-Insecure-Requests': '1',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 zc_core/1.70.3741.400 QQBrowser/10.5.3863.400',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'Accept-Encoding': 'gzip, deflate',
                'Accept-Language': 'zh-CN,zh;q=0.9',
            }
        )
        session_id = r.cookies.get('SESSION', '')
        logger.info('加载SESSION: session=%s' % session_id)
        if session_id:
            self.session_pool.append(session_id)
